/**
 * 
 */
package se.chalmers.spexet.booking.model;

import java.util.*;

import se.chalmers.spexet.booking.common.*;

/**
 * @author Winquman
 *
 */
public class Order {
	private GregorianCalendar created, completed;
	private ArrayList<Ticket> tickets;
	private Payment payed;
	private User givenBy;
	private final int orderid;
	private SalesPeriod period;
	
	public Order(int orderID) {
		created = (GregorianCalendar) GregorianCalendar.getInstance();
		this.orderid = orderID;
		payed = null;
	}

	// This method may return null!
	public Payment getPayment() {
		return payed;
	}
	
	
	public void finalize(Payment p, SalesPeriod s) throws InvalidOrderModificationException {
		if(payed != null)
			throw new InvalidOrderModificationException("Tried to finalize already finalized order:" + this);
		
		Iterator<Ticket> it = tickets.iterator();
		int sum = 0;
		
		while(it.hasNext()) {
			Ticket t = it.next();
			sum = sum + ModelSettings.getPrice(t.getTicketType()); 
		}
		
		if(sum != p.sum)
			throw new InvalidOrderModificationException("Tried to finalize order " + this + " with wrong payment:"
					+ " Expected " + sum + "but recieved payment for " + p.sum); 
			
		payed = p;
		
		it = tickets.iterator();
		
		try {
			while(it.hasNext()) {
				Ticket t = it.next();
				t.finalize(this);
			}
		} catch (InvalidOrderModificationException e) {
			payed = null;
			it = tickets.iterator();
			while(it.hasNext()) {
				Ticket t = it.next();
				try {
					t.cancelOrder(this);
				} catch (InvalidOrderModificationException f) {
					;
				}
			}
			InvalidOrderModificationException f = new InvalidOrderModificationException("Tried to finalize order "
					+ this + ", but failed to finalize one or more tickets.");
			f.initCause(e);
			throw f;
		}
		
		period = s;
		completed = (GregorianCalendar) GregorianCalendar.getInstance();
	}
	
	public boolean isFinalized() {
		if(payed == null)
			return false;
		else
			return true;
	}
}
